import axios from 'axios'
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { history } from "./history";
const service = axios.create({
  baseURL: `http://geek.itheima.net/v1_0`, // url = base url + request url
  timeout: 5000
  // withCredentials: true // send cookies when cross-domain requests
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.message !== "OK") {
      message.error(res.message || 'Error');
      return Promise.reject(res)
    } else {
      return response.data

    }
  },
  (error) => {
    if (error.response.status === 401) {
      localStorage.removeItem('token')
      history.push('/')
    }
    message.error(error.request.response || error.message)
    console.log(error);
    return Promise.reject(error)
  }
)

export default service